package com.duowei.kitchenshow.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.duowei.kitchenshow.R;
import com.duowei.kitchenshow.adapter.RvBottomAdapter;
import com.duowei.kitchenshow.adapter.RvLeftAdapter;
import com.duowei.kitchenshow.adapter.RvRightAdapter;
import com.duowei.kitchenshow.bean.Cfpb;
import com.duowei.kitchenshow.bean.Cfpb_item;
import com.duowei.kitchenshow.bean.Cfpb_lbbm;
import com.duowei.kitchenshow.event.HttpResponse;
import com.duowei.kitchenshow.httputils.Post;
import com.duowei.kitchenshow.service.Net;
import com.duowei.kitchenshow.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class MainFragment extends BaseMainFragment {
    private String sql2;
    private List<Cfpb> mCfpbList=new ArrayList<>();
    private List<Cfpb_item>mItemList=new ArrayList<>();
    private List<Cfpb_lbbm> mCfpbLbbms=new ArrayList<>();

    private String inputMsg="";

    private RvLeftAdapter mLeftAdapter=new RvLeftAdapter(R.layout.leftadapter_item,mCfpbList);
    private RvRightAdapter mRightAdapter=new RvRightAdapter(R.layout.rightadapter_item,mItemList);
    private RvBottomAdapter mBottomAdapter=new RvBottomAdapter(mCfpbLbbms);

    private String lbbm="";
    public static String mXmbh;
    private int index=0;

//    private int mLength=0;
//    private float mOutTime=0;
//    private KeySound mSound;

    public MainFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        mSound = KeySound.getContext(getActivity());

        sql2="select D.lbbm,D.lbmc,sum(A.sl)as sl from cfpb A LEFT JOIN JYXMSZ J LEFT JOIN DMJYXMSSLB D ON J.LBBM=D.LBBM ON A.XMBH=J.XMBH where A.XDSJ BETWEEN DATEADD(mi,-180,GETDATE()) " +
                "AND GETDATE() and (isnull(A.sl,0)-isnull(A.tdsl,0))>0 and "+ Net.kitchens+" group by D.lbbm,D.lbmc|";

        setSql(getSql1(lbbm)+sql2);
        setLeftAdapter(mLeftAdapter);
        setRightAdapter(mRightAdapter);
        setBottomAdapter(mBottomAdapter);

        mLeftAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                mXmbh = mCfpbList.get(i).getXmbh();
                brushLeftAdapter();

                notifyRightAdapter(mCfpbList.get(i).getItemList());
            }
        });
        mBottomAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                showLoad();
                index=0;
                lbbm=mCfpbLbbms.get(i).getLbbm();
                Post.getInstance().postCfpb(getSql1(lbbm)+sql2);
                setSql(getSql1(lbbm)+sql2);
            }
        });
    }

    private void brushLeftAdapter() {
        int num=-1;
        for(int j=0;j<mCfpbList.size();j++){
            if(mXmbh.equals(mCfpbList.get(j).getXmbh())){
                mCfpbList.get(j).setClick(true);
                num=j;
            }else{
                mCfpbList.get(j).setClick(false);
            }
        }
        if(num!=-1){
            index=num;
        }else{
            index=0;
        }

        if(TextUtils.isEmpty(inputMsg)){
            notifyLeftAdapter(mCfpbList);
        }else{
            searchCfpb(inputMsg);
        }
    }

    public void searchCfpb(String input){
        inputMsg=input;
        if(TextUtils.isEmpty(inputMsg)){
            Post.getInstance().postCfpb(getSql1(lbbm)+sql2);
            return;
        }
        index=0;
        for(int i=mCfpbList.size()-1;i>=0;i--){
            Cfpb cfpb = mCfpbList.get(i);
            if(!cfpb.getPy().toUpperCase().contains(inputMsg)&&!cfpb.getXmbh().contains(inputMsg)){
                mCfpbList.remove(cfpb);
            }
        }
        notifyLeftAdapter(mCfpbList);
    }

    @Subscribe
    public void getHttpResponse(HttpResponse event){
        hideLoad();
        mCfpbList.clear();
        String response = event.getResponse().replaceAll("\\\\",",");
        if(response.equals("]]")||response.equals("]")){
            mCfpbLbbms.clear();
            mItemList.clear();
            notifyLeftAdapter(mCfpbList);
            notifyRightAdapter(mItemList);
            notifyBottomAdapter(mCfpbLbbms);
            return;
        }
        setTopAdapter(response);

        setBottomAdapter(response);
    }

    private void setBottomAdapter(String response) {
        String rback=response.substring(response.lastIndexOf("["),response.length());
        if(!TextUtils.isEmpty(rback)&&!rback.equals("]")){
            Type type = new TypeToken<List<Cfpb_lbbm>>() {}.getType();
            try{
                mCfpbLbbms = new Gson().fromJson(rback, type);
                mCfpbLbbms.add(0, new Cfpb_lbbm("", "全部", 0, false));
                for (int i = 0; i < mCfpbLbbms.size(); i++) {
                    if (lbbm.equals(mCfpbLbbms.get(i).getLbbm())) {
                        mCfpbLbbms.get(i).setClick(true);
                    } else {
                        mCfpbLbbms.get(i).setClick(false);
                    }
                }
                notifyBottomAdapter(mCfpbLbbms);
            }catch (JsonSyntaxException e){
                ToastUtil.showToast(rback);
            }
        }
    }

    private void setTopAdapter(String response) {
        String rfront;
        if(response.endsWith("]]")){
            rfront=response.substring(0,response.indexOf("]]")+1);
        }else{
            rfront=response.substring(0,response.indexOf("][ {")+1);
        }
        if(rfront.equals("]")){
            mCfpbList.clear();
            mItemList.clear();
            brushLeftAdapter();
            notifyRightAdapter(mItemList);
            return;
        }
        try {
            Cfpb[] cfpb = new Gson().fromJson(rfront, Cfpb[].class);
            setCfpb(cfpb);
            String str = "";
            for (int i = 0; i < cfpb.length; i++) {
                //抓取每个单品所包含的餐桌数据集
                for (int j = 0; j < cfpb.length; j++) {
                    if ((cfpb[j].getXmbh()).equals(cfpb[i].getXmbh())) {
                        if(cfpb[j].getPz().contains("&lt;")&&cfpb[j].getPz().contains("&gt;")){
                            cfpb[j].setPz(cfpb[j].getPz().replaceAll("&lt;", "<").replaceAll("&gt;", ">"));
                        }
                        Cfpb_item cfpb_item = new Cfpb_item(cfpb[j].getXmbh(),cfpb[j].getXmmc(),cfpb[j].getCzmc(),
                                cfpb[j].getSl(), cfpb[j].getFzs(),cfpb[j].getCssj(),cfpb[j].getXdsj(),cfpb[j].getYhmc(),
                                cfpb[j].getXH(), cfpb[j].getPz(),cfpb[j].getPos(),cfpb[j].getDw(),cfpb[j].getBy10(),cfpb[j].getXszt());
                        List<Cfpb_item> list = cfpb[i].getItemList();
                        list.add(cfpb_item);
                        cfpb[i].setItemList(list);
                    }
                }
                //按单品编号不同进行分组
                if (!str.contains(cfpb[i].getXmbh())) {
                    mCfpbList.add(cfpb[i]);
                    str = str + cfpb[i].getXmbh() + "-";
                }
            }

            if(TextUtils.isEmpty(mXmbh)&&mCfpbList.size()>0){
                mXmbh=mCfpbList.get(0).getXmbh();
                notifyRightAdapter(mCfpbList.get(0).getItemList());
            }
            brushLeftAdapter();
            notifyRightAdapter(mCfpbList.get(index).getItemList());
        }catch (JsonSyntaxException e){
            ToastUtil.showToast(rfront);
        }
    }

    private String getSql1(String lbbm){
        if(TextUtils.isEmpty(lbbm)){
            return "select A.XH,A.wmdbh,A.xmbh,LTrim(A.xmmc)as xmmc,A.dw,(isnull(A.sl,0)-isnull(A.tdsl,0)-isnull(A.YWCSL,0))sl," +
            "A.pz,CONVERT(varchar(100), a.xdsj, 120)as xdsj,A.BY1 as czmc,datediff(minute,A.xdsj,getdate())fzs,A.yhmc,isnull(A.xszt,'')xszt,A.ywcsl,j.py,isnull(j.by13,9999999)cssj," +
            "A.by9,A.by10,A.pos,A.by1,A.by2,isnull(A.sfyxzz,'0')sfyxzz from cfpb A LEFT JOIN JYXMSZ J ON A.XMBH=J.XMBH " +
            "where A.XDSJ BETWEEN DATEADD(mi,-180,GETDATE()) AND GETDATE() and (isnull(A.sl,0)-isnull(A.tdsl,0))>0 and "+Net.kitchens+" order by A.xdsj,A.xmmc|";
        }else{
            return "select A.XH,A.wmdbh,A.xmbh,LTrim(A.xmmc)as xmmc,A.dw,(isnull(A.sl,0)-isnull(A.tdsl,0)-isnull(A.YWCSL,0))sl,A.pz,CONVERT(varchar(100), a.xdsj, 120)as xdsj,A.BY1 as czmc," +
                    "datediff(minute,A.xdsj,getdate())fzs,A.yhmc,isnull(A.xszt,'')xszt,A.ywcsl,j.py,isnull(j.by13,9999999)cssj,A.by9,A.by10,A.pos,A.by1,A.by2,isnull(A.sfyxzz,'0')sfyxzz " +
                    "from cfpb A LEFT JOIN JYXMSZ J LEFT JOIN DMJYXMSSLB D ON J.LBBM=D.LBBM ON A.XMBH=J.XMBH where A.XDSJ BETWEEN DATEADD(mi,-180,GETDATE()) AND GETDATE() " +
                    "and (isnull(A.sl,0)-isnull(A.tdsl,0))>0 and "+Net.kitchens+" and D.lbbm='"+lbbm+"'order by A.xdsj,A.xmmc|";
        }
    }
}
